package com.yanqu.road.dao.impl.relatives;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.relatives.RelativesLetter;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RelativesLetterDaoImpl extends TempDataObjectDao<RelativesLetter> {


    public Long getMaxLetterId() {
        String sql = "select ifnull(max(id),0) as maxId from t_u_relatives_letter";
        ResultSet rs = null;
        CallableStatement call = null;
        long maxId = 0L;
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                maxId = rs.getLong("maxId");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return maxId;
    }
    public boolean seeLetter(long letterId) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_relatives_letter SET isShow=1 where id=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, letterId);
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    public Map<Long, List<RelativesLetter>> getRelativesLetter(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, List<RelativesLetter>> dataMap = new ConcurrentHashMap<>();
        String sql = "select * from t_u_relatives_letter where (fromId = ? or toId = ?) and isDelete = 0 order by createTime";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setLong(2, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                RelativesLetter data = parse(rs);
                long relativesId;
                if (data.getFromId() == userId) {
                    relativesId = data.getToId();
                } else {
                    relativesId = data.getFromId();
                }
                List<RelativesLetter> dataList = dataMap.get(relativesId);
                if (dataList == null) {
                    dataList = new ArrayList<>();
                    dataMap.put(relativesId, dataList);
                }
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public List<RelativesLetter> getRelativesLetterList(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        List<RelativesLetter> dataList = new ArrayList<>();
        String sql = "select * from t_u_relatives_letter where (fromId = ? or toId = ?) and isDelete = 0 order by createTime";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, userId);
            call.setLong(2, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                RelativesLetter data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }
    @Override
    protected boolean addData(RelativesLetter data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_u_relatives_letter(id,fromId,toId,content,isShow,createTime,isDelete) values (?,?,?,?,?,?,?) ";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getId());
            call.setLong(i++, data.getFromId());
            call.setLong(i++, data.getToId());
            call.setString(i++, data.getContent());
            call.setBoolean(i++, data.isShow());
            call.setLong(i++, data.getCreateTime());
            call.setBoolean(i++, data.isDelete());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(RelativesLetter data) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_relatives_letter SET fromId=?,toId=?,content=?,isShow=?,createTime=?,isDelete=? where id=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getFromId());
            call.setLong(i++, data.getToId());
            call.setString(i++, data.getContent());
            call.setBoolean(i++, data.isShow());
            call.setLong(i++, data.getCreateTime());
            call.setBoolean(i++, data.isDelete());
            call.setLong(i++, data.getId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected RelativesLetter parseData(ResultSet rs) throws SQLException {
        RelativesLetter data = new RelativesLetter();
        data.setId(rs.getLong("id"));
        data.setFromId(rs.getLong("fromId"));
        data.setToId(rs.getLong("toId"));
        data.setContent(rs.getString("content"));
        data.setShow(rs.getBoolean("isShow"));
        data.setCreateTime(rs.getLong("createTime"));
        data.setDelete(rs.getBoolean("isDelete"));
        return data;
    }
}
